package com.gitee.hljdrl.utils.total;

import java.io.UnsupportedEncodingException;

public class TotalUtil {

    // 定义每个数据单位的字节大小
    private static final long KB = 1024;
    private static final long MB = KB * 1024;
    private static final long GB = MB * 1024;
    private static final long TB = GB * 1024; // 添加对TB的支持

    /**
     * 将字节大小格式化为可读的KB、MB、GB、TB字符串。
     *
     * @param bytes 字节大小
     * @return 格式化后的字符串
     */
    public static String formatSize(long bytes) {
        if (bytes < KB) {
            return bytes + " B";
        } else if (bytes < MB) {
            return String.format("%.2f KB", bytes / (double) KB);
        } else if (bytes < GB) {
            return String.format("%.2f MB", bytes / (double) MB);
        } else if (bytes < TB) {
            return String.format("%.2f GB", bytes / (double) GB);
        } else {
            return String.format("%.2f TB", bytes / (double) TB);
        }
    }

    public static int getByteSize(String input) {
        if (input == null) {
            return 0;
        }
        try {
            byte[] bytes = input.getBytes("UTF-8");
            return bytes.length;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 将传入的大小和单位转换为字节。
     *
     * @param size 大小
     * @param unit 单位，支持"B", "KB", "MB", "GB", "TB"
     * @return 对应的字节大小
     */
    public static long sizeToBytes(long size, String unit) {
        switch (unit.toUpperCase()) {
            case "KB":
                return size * KB;
            case "MB":
                return size * MB;
            case "GB":
                return size * GB;
            case "TB":
                return size * TB;
            default:
                return size; // 默认认为已经是字节
        }
    }

}
